import pymysql
import datetime
import random
import time


def insertNovel(id, title, imgUrl, anchor, author, typeId, introduction):
    try:
        # 打开数据库连接
        db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
        db.ping(reconnect=True)
        cursor = db.cursor()
        # SQL 插入语句
        sql = "INSERT INTO b_novel(id,title,cover_url,anchor,author,type_id,read_type,introduction,create_date) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        # 执行sql语句
        cursor.execute(sql, (id, title, imgUrl, anchor, author, typeId, 2, introduction, datetime.datetime.now()))
        # 提交到数据库执行
        db.commit()
        db.close()
    except Exception as e:
        # 如果发生错误则回滚
        print(e)
        db.rollback()


def insertNovelItem(title, novelId, number, url):
    try:
        # 打开数据库连接
        db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
        db.ping(reconnect=True)
        cursor = db.cursor()
        t = time.time()
        id = ''.join(str(i) for i in random.sample(range(0, 9), 9)) + str(t)
        # SQL 插入语句
        sql = "INSERT INTO b_novel_item(id,title,novel_id,number,url,create_date) VALUES (%s,%s,%s,%s,%s,%s)"
        # 执行sql语句
        cursor.execute(sql, (id, title, novelId, number, url, datetime.datetime.now()))
        # 提交到数据库执行
        db.commit()
        db.close()
    except Exception as e:
        # 如果发生错误则回滚
        print(e)
        db.rollback()


def checkIsExist(novelName):
    db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
    db.ping(reconnect=True)
    cursor = db.cursor()
    count_sql = "select count(1) from b_novel where title = '%s'" % (novelName)
    cursor.execute(count_sql)
    count = cursor.fetchall()
    if count[0][0] >0:
        return True
    else:
        return False

def delNovel(id):
    # 打开数据库连接
    try:
        db = pymysql.connect(host='139.196.196.131', port=3306, user='root', passwd='w1dewisd0m', db='hcloud-yunwei')
        db.ping(reconnect=True)
        cursor = db.cursor()
        del_sql = "delete from b_novel where id ="+id
        cursor.execute(del_sql)
        db.commit()
        db.close()
    except Exception as e:
        # 如果发生错误则回滚
        print(e)
        db.rollback()